// src/pages/index.js

// 扫描pages目录下所有page.vue
const pages = import.meta.glob('./**/page.vue')

// 先扫描出扁平结构
const routes = Object.keys(pages).map(key => {
    const path = key
        .replace(/^\.\//, '') // 去掉 ./
        .replace(/\/?page\.vue$/, ''); // 去掉 /page.vue

    return {
        path: `/${path}`,
        name: path,
        component: () => pages[key](),
        meta: {
            title: path.split('/').pop() || '首页'
        },
        hidden: false,
        whiteList: true
    };
});

// 插入父级节点
const allPaths = routes.map(route => route.path);
const parentRoutes = new Set();

allPaths.forEach(path => {
    // /a/b/c -> /a/b
    let currentPath = path.substring(0, path.lastIndexOf('/'));
    console.log('currentPath', currentPath)

    while (currentPath) {
        // 让 /a/b 的父路径 /a 也出现在路由中，从而支持菜单层级结构
        if (!parentRoutes.has(currentPath)) {
            routes.push({
                // /a
                path: currentPath,
                // name: -a
                name: currentPath.replace(/\//g, '-'),
                meta: {title: currentPath.split('/').pop()}
            });
            parentRoutes.add(currentPath);
        }
        // /a/b -> /a
        currentPath = currentPath.substring(0, currentPath.lastIndexOf('/'));
    }
});

console.log('scan routes', routes)
export default routes
